package com.ct.ah.lab.service.impl;

import com.ct.ah.lab.dao.CartDao;
import com.ct.ah.lab.entity.Cart;
import com.ct.ah.lab.entity.Product;
import com.ct.ah.lab.entity.User;
import com.ct.ah.lab.entity.vo.CartVo;
import com.ct.ah.lab.service.ICartService;
import com.ct.ah.lab.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("CartService")
public class CartServiceImpl implements ICartService {
    @Autowired
    private CartDao cartDao;
    @Autowired
    private IProductService productService;

    @Override
    public void save(Cart cart, User user) {
        //判断购物车中是否有该商品
        Map<String,Integer> map = new HashMap<>();
        map.put("uid",user.getUid());
        map.put("pid",cart.getPid());
        Cart newCart = cartDao.getByUidAndPid(map);
        if (newCart == null) {
            Product product = productService.getById(cart.getPid());
            Long price = new Long(product.getPrice());
            cart.setPrice(price);
            cart.setImge(product.getImage());
            cart.setModifiedUser(user.getUsername());
            cart.setCreatedUser(user.getUsername());
            cartDao.save(cart);
        } else {
            //修改商品数量
            newCart.setNum(newCart.getNum() + cart.getNum());
            newCart.setModifiedUser(user.getUsername());
            newCart.setCreatedUser(user.getUsername());
            cartDao.updateNum(newCart);
        }
    }

    @Override
    public List<CartVo> listCart(Integer uid) {
        return cartDao.listCart(uid);
    }

    @Override
    public List<CartVo> listCartByCids(List<Integer> cids) {
        return cartDao.listCartByCids(cids);
    }

    @Override
    public Boolean changeNum(Integer cid, Integer num, User user) {
        Cart oriCart = cartDao.getByCid(cid);
        if (oriCart.getNum() + num > 0){
            oriCart.setNum(oriCart.getNum() + num);
            oriCart.setModifiedUser(user.getUsername());
            oriCart.setCreatedUser(user.getUsername());
            cartDao.updateNum(oriCart);
            return true;
        }else{
            return false;
        }

    }

    @Override
    public void removeByCid(Integer cid) {
        cartDao.removeByCid(cid);
    }

    @Override
    public void removeByCidList(List<Integer> cidList) {
        cartDao.removeByCidList(cidList);
    }

    @Override
    public Integer findCid(Integer pid, Integer uid) {
        return cartDao.findCid(pid, uid);
    }

}
